In [133]:
import numpy as np
Create n-dimensional arrays with np.array
.
In [169]:
array = np.array([1, 2, 3])
array
Out[169]:
The type of arrays are always ndarray
.
In [135]:
type(array)
Out[135]:
In [136]:
[1, 2] + [2, 3]
Out[136]:
But numpy
arrays do mathematical operations across each element of the array.
In [137]:
np.array([1,2]) + np.array([2,3])
Out[137]:
numpy
arrays are fast at those operations across arrays due to the arrays having only the same type.
If we add a string to an integer array the whole array becomes a string.
In [138]:
arr = np.array([1, "2", 3])
arr
Out[138]:
Due to type mismatching we can no longer do mathematical operations on those arrays.
In [139]:
array + arr
In [140]:
arr = np.array([1, np.int("2"), 3])
arr
Out[140]:
In [141]:
array + arr
Out[141]:
In [142]:
array2d = np.array([[1,2, 3], [4, 5, 6]])
array2d
Out[142]:
In [143]:
array4d = np.array([[1, 2], [3, 4], [5, 6], [7,8]])
array4d
Out[143]:
In [144]:
print(array)
array[1]
Out[144]:
Python allows for a negative index to go backwards in the array. While going forward, indexes are zero-based. With a negative index, it is one-based.
In [145]:
array[-1]
Out[145]:
In [146]:
array[0:2:1]
Out[146]:
The step
syntax can be omitted.
In [147]:
array[0:2]
Out[147]:
The startIndex
can be omitted to indicate it starts from the beginning of the array.
In [148]:
array[:2]
Out[148]:
The same is true for the stopIndex
.
In [149]:
array[1:]
Out[149]:
Slicing can also be done with multi-dimensional arrays. Slices of each dimension is separated by a ,
.
In [150]:
print(array2d)
In [151]:
array2d[:, 0] # Return elements in all rows and only the first column
Out[151]:
In [152]:
array2d[0, :] # Return elements in the first row and all columns
Out[152]:
In [153]:
array2d[1, 1] # Return the element in the second row and the second column
Out[153]:
In [168]:
np.random.randint(5, size=2)
Out[168]:
The seed
method seeds the random generator to allow for reproducible results.
In [166]:
np.random.seed(0)